# -*- coding: utf-8 -*-
"""
MQTT配置和远程升级相关API接口
"""
import json
import traceback
from flask import Blueprint, request, jsonify, current_app
from app.model import MQTTConfig, UpgradeRecord, DeviceModel
from app.utils.database import db
from app.utils.mqtt_client import MQTTClient

# 创建蓝图
mqtt_bp = Blueprint('mqtt', __name__, url_prefix='/api/mqtt')


@mqtt_bp.route('/configs', methods=['GET'])
def get_mqtt_configs():
    """获取所有MQTT配置"""
    try:
        configs = MQTTConfig.get_all_configs()
        return jsonify({
            'code': 200,
            'message': '获取MQTT配置成功',
            'data': [config.to_dict() for config in configs]
        })
    except Exception as e:
        current_app.logger.error(f"获取MQTT配置失败: {str(e)}")
        return jsonify({
            'code': 500,
            'message': f'获取MQTT配置失败: {str(e)}'
        }), 500


@mqtt_bp.route('/configs', methods=['POST'])
def create_mqtt_config():
    """创建MQTT配置"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['config_name', 'broker', 'client_id', 'username', 'password']
        for field in required_fields:
            if field not in data or not data[field]:
                return jsonify({
                    'code': 400,
                    'message': f'缺少必填字段: {field}'
                }), 400
        
        config = MQTTConfig.create_config(data)
        
        return jsonify({
            'code': 200,
            'message': '创建MQTT配置成功',
            'data': config.to_dict()
        })
        
    except Exception as e:
        current_app.logger.error(f"创建MQTT配置失败: {str(e)}")
        if "UNIQUE constraint failed" in str(e):
            return jsonify({
                'code': 400,
                'message': '配置名称已存在'
            }), 400
        return jsonify({
            'code': 500,
            'message': f'创建MQTT配置失败: {str(e)}'
        }), 500


@mqtt_bp.route('/configs/<int:config_id>', methods=['PUT'])
def update_mqtt_config(config_id):
    """更新MQTT配置"""
    try:
        config = MQTTConfig.get_config_by_id(config_id)
        if not config:
            return jsonify({
                'code': 404,
                'message': 'MQTT配置不存在'
            }), 404
        
        data = request.get_json()
        updated_config = config.update_config(data)
        
        return jsonify({
            'code': 200,
            'message': '更新MQTT配置成功',
            'data': updated_config.to_dict()
        })
        
    except Exception as e:
        current_app.logger.error(f"更新MQTT配置失败: {str(e)}")
        return jsonify({
            'code': 500,
            'message': f'更新MQTT配置失败: {str(e)}'
        }), 500


@mqtt_bp.route('/configs/<int:config_id>', methods=['DELETE'])
def delete_mqtt_config(config_id):
    """删除MQTT配置"""
    try:
        success, message = MQTTConfig.delete_config(config_id)
        if not success:
            return jsonify({
                'code': 400 if "不能删除最后一个" in message else 404,
                'message': message
            }), 400 if "不能删除最后一个" in message else 404
        
        return jsonify({
            'code': 200,
            'message': message
        })
        
    except Exception as e:
        current_app.logger.error(f"删除MQTT配置失败: {str(e)}")
        return jsonify({
            'code': 500,
            'message': f'删除MQTT配置失败: {str(e)}'
        }), 500


@mqtt_bp.route('/configs/<int:config_id>', methods=['GET'])
def get_mqtt_config(config_id):
    """获取单个MQTT配置"""
    try:
        config = MQTTConfig.get_config_by_id(config_id)
        if not config:
            return jsonify({
                'code': 404,
                'message': 'MQTT配置不存在'
            }), 404
        
        return jsonify({
            'code': 200,
            'message': '获取MQTT配置成功',
            'data': config.to_dict()
        })
        
    except Exception as e:
        current_app.logger.error(f"获取MQTT配置失败: {str(e)}")
        return jsonify({
            'code': 500,
            'message': f'获取MQTT配置失败: {str(e)}'
        }), 500


@mqtt_bp.route('/upgrade', methods=['POST'])
def remote_upgrade():
    """远程升级设备"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['device_names', 'upgrade_message']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    'code': 400,
                    'message': f'缺少必填字段: {field}'
                }), 400
        
        # 导入服务类
        from app.services.mqtt_upgrade_service import MQTTUpgradeService
        
        # 验证升级消息格式
        upgrade_service = MQTTUpgradeService()
        is_valid, error_msg = upgrade_service.validate_upgrade_message(data['upgrade_message'])
        if not is_valid:
            return jsonify({
                'code': 400,
                'message': f'升级消息格式错误: {error_msg}'
            }), 400
        
        # 执行升级
        result = upgrade_service.send_upgrade_command(
            device_names=data['device_names'],
            upgrade_message=data['upgrade_message'],
            config_id=data.get('config_id')
        )
        
        if not result['success']:
            return jsonify({
                'code': 400,
                'message': result['error']
            }), 400
        
        return jsonify({
            'code': 200,
            'message': '远程升级请求处理完成',
            'data': {
                'upgrade_record_id': result['upgrade_record_id'],
                **result['result']
            }
        })
        
    except Exception as e:
        current_app.logger.error(f"远程升级失败: {str(e)}\n{traceback.format_exc()}")
        return jsonify({
            'code': 500,
            'message': f'远程升级失败: {str(e)}'
        }), 500


@mqtt_bp.route('/upgrade/records', methods=['GET'])
def get_upgrade_records():
    """获取升级记录"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        
        # 分页查询升级记录
        records = UpgradeRecord.query.order_by(
            UpgradeRecord.created_at.desc()
        ).paginate(
            page=page,
            per_page=per_page,
            error_out=False
        )
        
        return jsonify({
            'code': 200,
            'message': '获取升级记录成功',
            'data': {
                'records': [record.to_dict() for record in records.items],
                'pagination': {
                    'page': page,
                    'per_page': per_page,
                    'total': records.total,
                    'pages': records.pages,
                    'has_prev': records.has_prev,
                    'has_next': records.has_next
                }
            }
        })
        
    except Exception as e:
        current_app.logger.error(f"获取升级记录失败: {str(e)}")
        return jsonify({
            'code': 500,
            'message': f'获取升级记录失败: {str(e)}'
        }), 500


@mqtt_bp.route('/upgrade/records/<int:record_id>', methods=['GET'])
def get_upgrade_record(record_id):
    """获取单个升级记录详情"""
    try:
        record = UpgradeRecord.query.get(record_id)
        if not record:
            return jsonify({
                'code': 404,
                'message': '升级记录不存在'
            }), 404
        
        return jsonify({
            'code': 200,
            'message': '获取升级记录成功',
            'data': record.to_dict()
        })
        
    except Exception as e:
        current_app.logger.error(f"获取升级记录失败: {str(e)}")
        return jsonify({
            'code': 500,
            'message': f'获取升级记录失败: {str(e)}'
        }), 500


@mqtt_bp.route('/test-connection', methods=['POST'])
def test_mqtt_connection():
    """测试MQTT连接"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['broker', 'port', 'client_id', 'username', 'password']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    'code': 400,
                    'message': f'缺少必填字段: {field}'
                }), 400
        
        # 尝试连接MQTT
        try:
            mc = MQTTClient(
                data['broker'],
                data['port'],
                data['client_id'],
                data['username'],
                data['password']
            )
            
            # 这里可以添加实际的连接测试逻辑
            # mc.connect() 如果MQTTClient类有这个方法
            
            return jsonify({
                'code': 200,
                'message': 'MQTT连接测试成功',
                'data': {
                    'status': 'connected',
                    'broker': data['broker'],
                    'port': data['port']
                }
            })
            
        except Exception as e:
            return jsonify({
                'code': 400,
                'message': f'MQTT连接测试失败: {str(e)}'
            }), 400
        
    except Exception as e:
        current_app.logger.error(f"MQTT连接测试失败: {str(e)}")
        return jsonify({
            'code': 500,
            'message': f'MQTT连接测试失败: {str(e)}'
        }), 500 